import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'df_ronda_printer_platform_interface.dart';

/// An implementation of [DfRondaPrinterPlatform] that uses method channels.
class MethodChannelDfRondaPrinter extends DfRondaPrinterPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('df_ronda_printer');

  @override
  Future<String?> getPlatformVersion() async {
    final version = await methodChannel.invokeMethod<String>(
      'getPlatformVersion',
    );
    return version;
  }

  @override
  Future<String> connectDevice(String printAddr) async {
    final result = await methodChannel.invokeMethod<String>('connectDevice', {
      'printAddr': printAddr,
    });
    if (result == null) {
      throw PlatformException(
        code: 'ERROR',
        message: 'Failed to connect to device',
      );
    }
    return result;
  }

  @override
  Future<String> closeDevice() async {
    final result = await methodChannel.invokeMethod<String>('closeDevice');
    if (result == null) {
      throw PlatformException(code: 'ERROR', message: 'Failed to close device');
    }
    return result;
  }

  @override
  Future<void> printAscii(String printString) async {
    try {
      await methodChannel.invokeMethod('printAscii', {
        'printString': printString,
      });
    } on PlatformException catch (e) {
      throw Exception('Failed to print ASCII: ${e.message}');
    }
  }
}
